import router, { layourRoutes } from './index'
import { defineAsyncComponent } from 'vue'
import store from '@/store'
// 加载中 组件
import loadingComponent from '@/components/loading/index.vue'

import { getMenus } from '@/api/menu'
import { mapTwoLevelRouter } from '../unit/router'

const layout = () => import('@/components/layout.vue')

// 加载所有组件
function loadComponents() {
  return import.meta.glob('../views/**/*.vue')
}
const asynComponents = loadComponents()

// 动态加载组件
function getComponent(route) {
  return asynComponents['../views' + route.menuUrl + '.vue']
  // return defineAsyncComponent({
  //   loader: asynComponents['../views' + route.menuUrl + '.vue'],
  //   loadingComponent: loadingComponent
  // })
}

// 设置白名单
const whiteRoutes = ['/login', '/register', '/404'];

// 是否登录
function isLogin() {
  return !!store.getters["user/isLogin"]
}

// 是否已经加载菜单
function isNotLoadedMenu() {
  return !!store.getters['menu/isEmptyPermissionRoutes']
}

// 处理菜单
function handleMenu2Route(menus) {
  const tempRoutes = []
  menus.forEach(it => {
    const route = {
      path: it.menuUrl,
      name: getNameByUrl(it.menuUrl),
      hidden: !!it.hidden,
      redirect: it.redirect || '',
      component: isMenu(it.menuUrl) ? layout : getComponent(it),
      meta: {
        title: it.menuName,
        enTitle: it.menuEnName || '',
        affix: !!it.affix,
        cacheable: !!it.cacheable,
        icon: it.icon || 'menu-outlined',
        badge: it.badge,
      }
    }
    if (it.children && it.children.length > 0) {
      route.children = handleMenu2Route(it.children)
    }
    tempRoutes.push(route)
  })
  return tempRoutes
}

function isMenu(path) {
  return getCharCount(path, '/') === 1
}

function getCharCount(str, char) {
  const regex = new RegExp(char, 'g')
  const result = str.match(regex)
  return !result ? 0 : result.length
}

// 通过url获取name
function getNameByUrl(url) {
  const temp = url.split('/')
  !temp[0] && temp.splice(0, 1)
  return temp.join('_')
}

function initPermissionRoutes(routes) {
  store.dispatch("menu/initPermissionRoutes", routes)
}

router.beforeEach(async (to) => {
  if (whiteRoutes.includes(to.path)) { // 白名单
    return true
  }
  if (!isLogin()) { // 没有登录
    return {
      path: '/login',
      query: { redirect: to.fullPath }
    }
  }
  if (isNotLoadedMenu()) {
    const accessRoutes = []
    // 获取菜单
    const apiGetMenus = await getMenus()
    const tempRoutes = handleMenu2Route(apiGetMenus)
    accessRoutes.push(...tempRoutes)
    const mapRoutes = mapTwoLevelRouter(accessRoutes)
    // 添加路由
    mapRoutes.forEach((it) => {
      router.addRoute(it)
    })
    // 添加404
    router.addRoute({
      path: '/:pathMatch(.*)*',
      redirect: '/404',
      hidden: true
    })
    initPermissionRoutes([...layourRoutes, ...accessRoutes])
    store.dispatch("webset/changeMenuSelected", to.fullPath)
    return { ...to, replace: true }
  }
  store.dispatch("webset/changeMenuSelected", to.fullPath)
  return true
})